package com.wa.async;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;

import javax.annotation.Resource;

/**
 *   1.@Async同类直接调用没结果,需要从容器中获取自己类再调用才有效果
 *   2.调用别的类方法带有@Async,有效果
 */
//@RestController
//@RequestMapping("/async")
public class AsyncController {

    @Resource
    private AsyncService asyncService;

    /** 本类标注@Async是同步
     *  http://127.0.0.1:8888/async/testTheClaasAsync
     * @return
     */
//    @RequestMapping("/testTheClaasAsync")
    public String testTheClaasAsync(){
        //同步
        updateReadCount();
        return "Hello, Spring Boot 2!"+"你好：";
    }

    /** 本类标注@Async,通过SpringUtil获取的执行还是异步
     *  http://127.0.0.1:8888/async/testTheClaasSpringAsync
     * @return
     */
//    @RequestMapping("/testTheClaasSpringAsync")
    public String testTheClaasSpringAsync(){
        AsyncController bean = SpringUtil.getBean(AsyncController.class);
        //异步
        bean.updateReadCount();
        return "Hello, Spring Boot 2!"+"你好：";
    }

    /** 其他类方法标注@Async是异步
     *  http://127.0.0.1:8888/async/testOtherClaasAsync
     * @return
     */
//    @RequestMapping("/testOtherClaasAsync")
    public String testOtherClaasAsync(){
        //异步
        asyncService.updateReadCount();
        return "Hello, Spring Boot 2!"+"你好：";
    }



    @Async("customExecutor")
    public void updateReadCount() {
        // TODO 模拟耗时操作
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("更新文章阅读量线程"+Thread.currentThread().getName());
    }
}
